/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.evosoft.vista.panel.empresa;

import com.evosoft.facade.FacadeFactory;
import com.evosoft.linker.App;
import com.evosoft.model.Empresa;
import com.evosoft.model.Persona;
import com.evosoft.util.Sesion;
import com.evosoft.vista.panel.usuarios.ListaUsuarios;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Silex RPR
 */
public class ListaEmpresa extends javax.swing.JPanel {

    /**
     * Creates new form ListaDistribuidor
     */
    public ListaEmpresa() {
        initComponents();
        Persona personaEnSesion = Sesion.getInstance().getPersonaEnSesion();
        jLabel3.setText(personaEnSesion.getNombre() + " " + personaEnSesion.getApellido());
        if(personaEnSesion.getEmpresa().getTipo() != null)
           jLabel4.setText(personaEnSesion.getEmpresa().getNombre() + " ("+personaEnSesion.getEmpresa().getTipo().getNombre()+")");
        else
           jLabel4.setText(personaEnSesion.getEmpresa().getNombre() + " (Administrador de Sistema)");
        jLabel6.setText(personaEnSesion.getRol().getNombre());
        listaTable.setModel(model);
        listaTable.setColumnSelectionAllowed(false);
        listaTable.setRowSelectionAllowed(true);

        model.addColumn("Nombre");
        model.addColumn("NIT");
        
        listaTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        
        if(!personaEnSesion.getRol().getCreaEmpresa()) {
            nuevoButton.setEnabled(false);
            jButton2.setEnabled(false);
            jButton1.setEnabled(false);
        }
        
        listaTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2 && !e.isConsumed()) {
                    e.consume();
                    App.getInstance().getMainWindow().getAppTabPanel().setComponentAt(0, new CrearEmpresa(null));
                }
            }
        });
        
        updateListModel();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        nuevoButton = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        listaTable = new javax.swing.JTable();

        nuevoButton.setText("Nuevo");
        nuevoButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nuevoButtonActionPerformed(evt);
            }
        });

        jButton2.setText("Eliminar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel1.setText("Nombre: ");

        jLabel2.setText("Empresa:");

        jLabel3.setText("jLabel3");

        jLabel4.setText("jLabel4");

        jButton1.setText("Modificar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton3.setText("Detalles");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jLabel5.setText("Rol:");

        jLabel6.setText("jLabel6");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel6)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(nuevoButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(jLabel3))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(jLabel4))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel5)
                            .addComponent(jLabel6))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(nuevoButton, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 41, Short.MAX_VALUE)
                            .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                .addContainerGap())
        );

        listaTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(listaTable);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 758, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 271, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    
    private String nitSeleccionado(){
        String nit = "";
        if(listaTable.getSelectedRow() == -1) {
            JOptionPane.showMessageDialog(this, "NO seleccionó ningún dato", "Error", JOptionPane.ERROR_MESSAGE);
        }
        else {
            int fila = listaTable.getSelectedRow();
            //Se selecciona la columna 1 porque ahi esta el nit, si se van a agregar mas columnas toca al final
            nit = (String) listaTable.getModel().getValueAt(fila, 1);
        }
        return nit;
    }
    
    /*Botón para ver los detalles de una empresa*/
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        String nitSeleccionado = nitSeleccionado();
        if(nitSeleccionado.compareTo("") != 0) {
            App.getInstance().getMainWindow().getAppTabPanel().setComponentAt(0, new DetallesEmpresa(nitSeleccionado));
        }
    }//GEN-LAST:event_jButton3ActionPerformed

    private void nuevoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nuevoButtonActionPerformed
        App.getInstance().getMainWindow().getAppTabPanel().setComponentAt(0, new CrearEmpresa(null));
    }//GEN-LAST:event_nuevoButtonActionPerformed

    /*Botón para eliminar una empresa*/
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        String nitSeleccionado = nitSeleccionado();
        if(nitSeleccionado.compareTo("") != 0) {
            try {
                int response = JOptionPane.showConfirmDialog(null, "Está seguro de eliminar esta empresa y todos sus usuarios?", "Confirmación",
                JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
                if (response == JOptionPane.YES_OPTION) {
                    Empresa empresa = FacadeFactory.getInstance().getEmpresaFacade().obtenerEmpresaPorNit(nitSeleccionado);
                    FacadeFactory.getInstance().getEmpresaFacade().eliminarEmpresa(empresa.getId(), Sesion.getInstance().getPersonaEnSesion().getId());
                }
                
            } catch (Exception ex) {
                Logger.getLogger(ListaEmpresa.class.getName()).log(Level.SEVERE, null, ex);
            }
            
            //Se usa para eliminar el tab de usuarios, volverlo a crear y de esta manera actualizarlo despues de eliminar usuarios
            App.getInstance().getMainWindow().getAppTabPanel().remove(1);
            App.getInstance().getMainWindow().getAppTabPanel().addTab("Usuarios", new ListaUsuarios());
            updateListModel();
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    //Se usa para modificar la empresa
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        String nitSeleccionado = nitSeleccionado();        
        if(nitSeleccionado.compareTo("") != 0) {
            CrearEmpresa modificarDistribuidor = new CrearEmpresa(nitSeleccionado);
            App.getInstance().getMainWindow().getAppTabPanel().setComponentAt(0, modificarDistribuidor);
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    public final void updateListModel() {
        
        if (model.getRowCount() > 0) {
            for (int i = model.getRowCount() - 1; i > -1; i--) {
                model.removeRow(i);
            }
        }
        
        
        
        List<Empresa> lista = new ArrayList<Empresa>();
        try {
            Persona personaEnSesion = Sesion.getInstance().getPersonaEnSesion();
            Empresa empresaSesion = personaEnSesion.getEmpresa();
            lista = FacadeFactory.getInstance().getEmpresaFacade().obtenerEmpresasDependientes(empresaSesion.getId());
        } catch (Exception ex) {
            Logger.getLogger(ListaEmpresa.class.getName()).log(Level.SEVERE, null, ex);
        }

        for(Empresa e : lista) {
            model.addRow(new Object[] {e.getNombre(), e.getNit()});
        }

        listaTable.setModel(model);
    }
    
    private DefaultTableModel model = new DefaultTableModel() {
        @Override
        public boolean isCellEditable(int row, int column) {
            return false;
        }
    };
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable listaTable;
    private javax.swing.JButton nuevoButton;
    // End of variables declaration//GEN-END:variables
}
